<?php
namespace Api\Model;
use Think\Model;
use Com\Message;
class OrderModel extends Model {
    
    const ORDER_UNCONFIRMED = 0;
    const ORDER_CONFIRMED = 1;
    const ORDER_COMPLATED = 2;
    const ORDER_CANNELED = 3;
    const SHIPPING_UNSHIPPED = 0;
    const SHIPPING_PARTIALSHIPMENT = 1;
    const SHIPPING_SHIPPED = 2;
    const REVIEW_UNREVIEWED = 0;
    //--支付状态
//    const ORDER_REFUND_SUCCEED = 5; //退款成功
    const ORDER_REFUND_FAIL = '4';    //退款失败
    const ORDER_APPLY_REFUND = '3'; //申请退款
    const ORDER_REFUND = '2';      //已退款
    const ORDER_PAY = '1';        //已付款
    const ORDER_UNPAY = '0';      //未付款
    const REVIEW_REVIEWED = '1';
    
    protected $_auto = array (
        array('uid', API_UID, self::MODEL_INSERT),
        array('order_status', 0, self::MODEL_INSERT),
        array('shipping_status', 0, self::MODEL_INSERT),
        array('review_status', 0, self::MODEL_INSERT),
        array('status', 0, self::MODEL_INSERT),
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('shipping_time', 0, self::MODEL_INSERT),
        array('confirm_time', 0, self::MODEL_INSERT),
        array('complate_time', 0, self::MODEL_INSERT)
    );

    /**
     * 创建订单号
     * @return string
     */
    protected function build_order_no() {
        mt_srand((double) microtime() * 1000000);
        return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * 赠送积分
     * @param $order_id
     */
    public function giveScore($order_id){
        $products = D('order_product')->where('order_id='.$order_id)->select();
        foreach ($products as $product){
            if($product['score']>0) {
                $shop = D('shop')->where('id='. $product['shop_id'])->getField('uid');
                if(!$shop){
                    D ( 'member' )->where ( 'uid=' . API_UID )->setInc ( 'score', $product[ 'score' ] );
                }else{
                    //$shop_score = D('member')->where('uid='.$shop)->getField('score');
                    $username=M('ucenter_member')->where('id='.$shop)->getField('username');
                    $shop_score=M('users')->where('user_login='.$username)->getField('coin');
                    if($shop_score>$product['score']){
                        //--减少商家积分数量
                        D('member')->where('uid='.$shop)->setDec('score',$product['score']);
                        //--增加商户赠送积分
                        D('shop')->where('uid='.$shop)->setInc('give_score',$product['score']);
                        //增加用户积分
                        D ( 'member' )->where ( 'uid=' . API_UID )->setInc ( 'score', $product[ 'score' ] );
                    }else{
                        //TODO 积分不足，是个问题啊
                        //--商家积分不足，下架该商品
                        M('product')->where('id='.$product['product_id'])->setfield('status',0);
                    }
                }
            }
        }
    }

    /**
     * @param $res 购买成功，用户回调
     */
    public function pay($res,$paytype=20){

        //file_put_contents('./res.txt',json_encode($res));
        if($res){
           // file_put_contents('./true.txt',json_encode($_POST));
            $trade_no = $res['trade_no'];
            if(substr($trade_no,0,3)=='MG_'){
                $order = D('merge_order')->where('order_no="' . $trade_no . '"')->find();
                if($order){
                    if($order['price'] == $res['total_fee']){
                        $order_ids = explode(',',$order['order_ids']);
                        foreach ($order_ids as $order_id){
                            $order1=M('order')->where('id='.$order_id)->find();
                            if($order1['pay_status']){
                                echo 'SUCCESS';
                                break;
                            }
                            //消费记录
                            payrecord($order1['uid'],$order_id,$order1['price'],3);
                            $this->Where('id="'.$order_id.'"')->Save(array(
                                'status'     => 1,
                                'pay_status' => 1,
                                'pay_time'   => time (),
                                'pay_style' => $paytype,//order_style 支付方式 10 积分，20 支付宝，30 微信 40 余额支付

                            ));
                            M('order_product')->where(array('order_id' => $order_id))->save(array('create_time' => time(), 'update_time' => time()));
                            $order = M('order')->where('id='.$order_id)->find();

                            $productid_result = M('order_product')->field('product_id,quantity')->where(array('order_id' => $order_id))->find();

                            $userid_result = M('product')->field('uid')->where(array('id' => $productid_result['product_id']))->find();
                            $phone_result = M('ucenter_member')->field('username')->where(array('id' => $userid_result['uid']))->find();
                            $sales = M('product')->where(array('id' => $productid_result['product_id']))->getField('sales');
                            M('product')->where(array('id' => $productid_result['product_id']))->save(array('sales' => intval($sales) + $productid_result['quantity']));
                            M('product')->where(array('id' => $productid_result['product_id']))->setDec('quantity',$productid_result['quantity']);
                            file_put_contents('phone.txt',json_encode($phone_result['username']), FILE_APPEND);
                            Message::send($phone_result['username'],'#code#='.$order['order_no'],'50603');
                        }
                        echo 'SUCCESS';
//                        D('merge_order')->where('order_no="' . $trade_no . '"')->delete();
                    }else{
                        file_put_contents ( './ff.txt', json_encode ( $_POST ) );
                    }
                }else{
                    file_put_contents ( './false.txt', json_encode ( $_POST ) );
                }
            }else {
                $total_fee = $res[ 'total_fee' ];
                file_put_contents('./order_no.txt',$trade_no);
                $order = $this->Where ( 'order_no="' . $trade_no . '"' )->find ();
                if ( $order ) {
                    if ( $order[ 'price' ] == $total_fee ) {
                        //消费记录
                        payrecord($order['uid'],$order['id'],$order['price'],3);
                            $res = $this->Where ( 'order_no="' . $trade_no . '"' )->Save ( [
                                'status'     => 1,
                                'pay_status' => 1,
                                'pay_time'   => time (),
                                'pay_style' => $paytype,//order_style 支付方式 10 积分，20 支付宝，30 微信 40 余额支付
                            ] );
                            if ( $res ) {
                                echo 'SUCCESS';
                            }
//                        }
                    }else{
                        file_put_contents ( './ff.txt', json_encode ( $_POST ) );
                    }
                } else {

                    file_put_contents ( './false.txt', json_encode ( $_POST ) );
                }
            }
        }else{
            file_put_contents('./fff.txt',json_encode($_POST));
        }
    }

    /**
     * 创建订单
     * @param $carts
     * @param $receiver
     *
     * @return array|bool
     */
    public function createOrder($carts, $receiver,$is_quick=false,$uid,$remarks) {
        if (empty($carts)) {
            return false;
        }
        $orders = array();
        //--是否为积分商品订单
        $is_score_product = 0;
        $score = 0;
        foreach ($carts as $cart) {
            $product_info = M('product')->where(array('status'=>1,'id'=>$cart['product_id']))->find();

            if ($product_info) {
                $product['product_id'] = $cart['product_id'];
                $product['product_title'] = $product_info['title'];
                if (intval($product_info['quantity']) - intval($cart['quantity']) < 0) {
                    $this->error = '商品库存不足';
                    return false;
                }
                $product['quantity'] = $cart['quantity'];
                $product['product_attr'] = '默认';
                $price = $product_info['price'];
                if ($cart['option_ids']) {
                    $option_ids = str2arr($cart['option_ids'], ',');
                    sort($option_ids, SORT_NUMERIC);
                    $product_attr_text = '';
                    foreach ($option_ids as $option_id) {
                        $option_pid = get_table_field($option_id, 'id', 'pid', 'product_option');
                        $product_attr_text .= get_table_field($option_pid, 'id', 'title', 'product_option') . ':';
                        $product_attr_text .= get_table_field($option_id, 'id', 'title', 'product_option') . ',';
                    }
                    $product['product_attr'] = substr($product_attr_text, 0, strlen($product_attr_text) - 1);
                    $option_ids = arr2str($option_ids, ',');
                    $product_option_price_info = M('product_option_price')->where(array('product_id'=>$cart['product_id'], 'product_option_id'=>$option_ids))->find();
                    if ($product_option_price_info) {
                        $price = $product_option_price_info['price'];
                    }
                }
                $product_total_price = $price * intval($cart['quantity']);
                if ($product_info['in_special_panic']) {
                    $product_panic_info = M('product_special_panic')->where(array('product_id'=>$cart['product_id']))->find();
                    $special_panic_info = M('special_panic')->where(array('id'=>$product_panic_info['special_panic_id'], 'status'=>1))->find();
                    if ($special_panic_info && $product_total_price >= $product_panic_info['condition_price']) {
                            $special_panic_result_starttime=strtotime(date('Y-m-d')." ".date('H:i:s',$special_panic_info['start_time']));
                            $special_panic_result_endtime=strtotime(date('Y-m-d')." ".date('H:i:s',$special_panic_info['end_time']));
                            if(($special_panic_result_starttime<=NOW_TIME) && ($special_panic_result_endtime>= NOW_TIME)){
                                $price = $price * $product_panic_info['discount'] * 0.1;
                                $product_total_price = $price * $cart['quantity'];
                            }
                        // if ($product_panic_info['condition_price'] > 0) {
                        //     $product_total_price >= $product_panic_info['condition_price'] && $price = $price * $product_panic_info['discount'] / 10;
                        // } else {
                        //     $price = $price * $product_panic_info['discount'] / 10;
                        // }
                        // $product_total_price = $price * intval($cart['quantity']);
                    }
                }
                $product['price'] = $price;
                $product['option_ids'] = $cart['option_ids'];
                $product['unit_price'] = $price;
                $product['shipping_status'] = 0;

                //--想订单商品表存储shop_id
                $product['shop_id'] = $product_info['shop_id'];
                $score += $product['score'] = $product_info['score']*$cart['quantity'];
                $orders[$product_info['uid']]['products'][] = $product;
                if (!isset($orders[$product_info['uid']])) {
                    $orders[$product_info['uid']]['price'] = 0;
                }
                $orders[$product_info['uid']]['price'] = $orders[$product_info['uid']]['price'] + $product_total_price;
            } else {
                $this->error = '您购买的商品【' . $product_info['title'] . '】已下架';
                return false;
            }
        }
        
        $returns = array();
        foreach ($orders as $order) {
            $products = $order['products'];
            foreach ($products as $product) {
                $product_id=$product['product_id'];
            }
            $pro = M('product')->where('id='.$product_id)->find();
            $data = $this->create();
            $data = array_remove($data, 'id');
            $data['remarks'] = $remarks;
            if(!$data['uid']){
                $data['uid']=API_UID;
                $data['create_time']=time();
                $data['confirm_time']=time();
                $data['order_status']=1;
            }
            $data['order_type'] = $pro['good_type'];
            $orderno = $this->build_order_no();
            $data['order_no'] = $orderno;
            $data['is_score_product'] = $is_score_product;
            $data['price'] = $order['price'];
            $user =M('member')->where('uid='.$uid)->find();
            if($order['price'] > $user['coin']){
                $this->error = '元宝不足';
                return false;
            }else{
                M('member')->where('uid='.$uid)->setDec('coin',$order['price']);
            }


            $data['pay_status'] = OrderModel::ORDER_PAY;
            $data['order_status'] = 1;
            $data['status'] = 1;
            $data['pay_time'] = time();
            $data['consignee'] = $receiver['realname'];
            $data['mobile'] = $receiver['mobile'];
            $data['province_id'] = $receiver['province_id'];
            $data['city_id'] = $receiver['city_id'];
            $data['area_id'] = $receiver['area_id'];
            $data['address'] = $receiver['address'];
            $res = $id = $this->add($data);
            if ($res === false){
                $this->error = '创建订单失败';
                return false;
            }
            //消费记录
            payrecord(API_UID,$id,$order['price'],4);
            if(!$is_quick)
                foreach ($carts as $cart) {
                    M('cart')->where(array('id'=>$cart['id']))->delete();
                }
            foreach ($products as $product){
                $product['order_id'] = $id;
                M('order_product')->add($product);
                M('product')->where(array('id'=>$product['product_id']))->setDec('quantity',intval($product['quantity']));
                M('product')->where(array('id'=>$product['product_id']))->setInc('sales',intval($product['quantity']));
            }
            D('message')->quickMessage(API_UID, MessageModel::TYPE_ORDER, '您的订单' . $orderno . '成功创建');
        }
        
        return true;
    }

    /**
     * 创建订单，虽然我不知道这是什么东东
     * @param $carts
     * @param $receiver
     *
     * @return array|bool
     */
    public function createScoreOrder($carts, $receiver,$is_quick=false) {
        if (empty($carts)) {
            return false;
        }
        $orders = array();
        //--是否为积分商品订单
        $is_score_product = 0;
        $score = 0;
//        response(-1,$carts);
        foreach ($carts as $cart) {
            $product_info = M('product')->where(array('status'=>1,'id'=>$cart['product_id']))->find();
            if($product_info['type']=='score'){
                $is_score_product = 1;
            }
            if ($product_info) {
                $product['product_id'] = $cart['product_id'];
                $product['product_title'] = $product_info['title'];
                if (intval($product_info['quantity']) - intval($cart['quantity']) < 0) {
                    $this->error = '商品【' . $product_info . '】库存不足';
                    return false;
                }
                $product['quantity'] = $cart['quantity'];
                $product['product_attr'] = '默认';
                $price = $product_info['price'];
                if ($cart['option_ids']) {
                    $option_ids = str2arr($cart['option_ids'], ',');
                    sort($option_ids, SORT_NUMERIC);
                    $product_attr_text = '';
                    foreach ($option_ids as $option_id) {
                        $option_pid = get_table_field($option_id, 'id', 'pid', 'product_option');
                        $product_attr_text .= get_table_field($option_pid, 'id', 'title', 'product_option') . ':';
                        $product_attr_text .= get_table_field($option_id, 'id', 'title', 'product_option') . ',';
                    }
                    $product['product_attr'] = substr($product_attr_text, 0, strlen($product_attr_text) - 1);
                    $option_ids = arr2str($option_ids, ',');
                    $product_option_price_info = M('product_option_price')->where(array('product_id'=>$cart['product_id'], 'product_option_id'=>$option_ids))->find();
                    if ($product_option_price_info) {
                        $price = $product_option_price_info['price'];
                    }
                }
                $product_total_price = $price * intval($cart['quantity']);
                if ($product_info['in_special_panic']) {
                    $product_panic_info = M('product_special_panic')->where(array('product_id'=>$cart['product_id']))->find();
                    $special_panic_info = M('special_panic')->where(array('id'=>$product_panic_info['special_panic_id'], 'status'=>1, 'start_time'=>array('elt',NOW_TIME), 'end_time'=>array('egt',NOW_TIME)))->find();
                    if ($special_panic_info) {
                        if (intval($product_panic_info['condition_price']) > 0) {
                            $product_total_price >= intval($product_panic_info['condition_price']) && $price = intval($price - $price * $product_panic_info['discount'] / 10);
                        } else {
                            $price = $price - ($price * $product_panic_info['discount'] / 10);
                        }
                        $product_total_price = $price * intval($cart['quantity']);
                    }
                }
                $product['price'] = $product_total_price;
                $product['option_ids'] = $cart['option_ids'];
                $product['unit_price'] = $price;
                $product['shipping_status'] = 0;

                //--想订单商品表存储shop_id
                $product['shop_id'] = $product_info['shop_id'];
                $score += $product['score'] = $product_info['score']*$cart['quantity'];
                $orders[$product_info['uid']]['products'][] = $product;
                if (!isset($orders[$product_info['uid']])) {
                    $orders[$product_info['uid']]['price'] = 0;
                }
                $orders[$product_info['uid']]['price'] = $orders[$product_info['uid']]['price'] + $product_total_price;
            } else {
//                dump($cart);
                $this->error = '您购买的商品【' . $product_info['title'] . '】已下架';
                return false;
            }
        }
//        response(-1,$orders);exit;
        $returns = array();
        foreach ($orders as $order) {
            $products = $order['products'];
//            print_r($products);
//            continue;
            $data = $this->create();
            $orderno = $this->build_order_no();
            $data['order_no'] = $orderno;
            $data['is_score_product'] = $is_score_product;
//	        $data['$score']
            $data['price'] = $order['price'];
            if($data['price']==0){
                $data['pay_status'] = OrderModel::ORDER_PAY;
                $data['order_status'] = 0;
            }else{
                $data['pay_status'] = OrderModel::ORDER_UNPAY;
                $data['order_status'] = 0;
            }
            $data['consignee'] = $receiver['realname'];
            $data['mobile'] = $receiver['mobile'];
            $data['province_id'] = $receiver['province_id'];
            $data['city_id'] = $receiver['city_id'];
            $data['area_id'] = $receiver['area_id'];

            //--使用积分数量
            $data['score_num'] = ceil($order['price']);

            $data['address'] = $receiver['address'];
            $res = $id = $this->add($data);
            if ($res === false) {
                response(-1,$data);
                $this->error = '未知错误';
                return false;
            }
            $returns[] = array('id'=>$id,'order_no'=>$orderno);
//            response(1,$returns);
            if(!$is_quick)
                foreach ($carts as $cart) {
                    M('cart')->where(array('id'=>$cart['id']))->delete();
                }
            foreach ($products as $product) {
                $product['order_id'] = $id;
                M('order_product')->add($product);
                M('product')->where(array('id'=>$product['product_id']))->setDec('quantity',intval($product['quantity']));
            }
//            addMessage()
            D('message')->quickMessage(API_UID, MessageModel::TYPE_ORDER, '您的订单' . $orderno . '成功创建');
        }

        return $returns;
    }



    public function getOrderStatusText($order) {
        if($order['order_status'] == self::ORDER_CANNELED){

            return '交易取消';
        }else
            if($order['pay_status']==self::ORDER_UNPAY){
            return '待付款';
        }elseif ($order['pay_status']==self::ORDER_APPLY_REFUND) {
            return '申请退款';
        }elseif($order['pay_status']==self::ORDER_REFUND){
            return '已退款';
        }
        else
        if ($order['order_status'] == self::ORDER_COMPLATED && $order['shipping_status'] == self::SHIPPING_SHIPPED && $order['review_status'] == self::REVIEW_REVIEWED) {
            return '交易完成';
        } elseif ($order['order_status'] == self::ORDER_COMPLATED && $order['shipping_status'] == self::SHIPPING_SHIPPED && $order['review_status'] == self::REVIEW_UNREVIEWED) {
            return '待评价';
        } elseif ($order['order_status'] == self::ORDER_CONFIRMED && $order['shipping_status'] == self::SHIPPING_SHIPPED) {
            return '已发货';
        } elseif ($order['order_status'] == self::ORDER_CONFIRMED && $order['shipping_status'] != self::SHIPPING_SHIPPED) {
            return '待发货';
        }else {
            return '';
        }
    }
}